import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/pages/site/site_device_list/access_device/views/infoHeaderView.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/brn_row1_delegate.dart';

import 'model/access_device_model.dart';
import 'model/device_type_detail_model.dart';
import 'model/device_type_model.dart';

class AccessDeviceController extends GetxController {
  final DeviceServices services = Get.put(DeviceServices());
  List<AccessDeviceModel> deviceUnitList = [];
  List<DeviceTypeModel> deviceTypeList = [];
  List<DeviceTypeDetailModel> deviceTypeDetailList = [];
  AccessProgressType type = AccessProgressType.normalInfo;
  AccessDeviceModel unitMode = AccessDeviceModel(); //保存选中的单元数据
  DeviceTypeModel typeModel = DeviceTypeModel(); //保存产品类型数据
  DeviceTypeDetailModel typeDetailModel = DeviceTypeDetailModel(); //保存产品型号数据
  // String deviceName = '';
  // String deviceSn = '';
  bool btnCanClick = false;
  late int siteId = 1;
  List<String> titleList = [
    ResKey.siteDeviceAccessOwningUnit.tr,
    ResKey.siteDeviceAccessProductType.tr,
    ResKey.siteDeviceAccessProductModel.tr,
    ResKey.deviceName.tr,
    ResKey.deviceSn.tr
  ];

  final TextEditingController unitController = TextEditingController();
  final TextEditingController deviceTypeController = TextEditingController();
  final TextEditingController deviceModelController = TextEditingController();
  final TextEditingController deviceNameController = TextEditingController();
  final TextEditingController deviceSnController = TextEditingController();
  bool isEmsSn = false;

  ///设备图片列表
  List<String> deviceImageList = [];
  @override
  void onInit() {
    if (Get.arguments != null) {
      siteId = Get.arguments['siteId'];
    }
    super.onInit();
  }

  @override
  void onReady() {
    Log.d('onReady==');
  }

  @override
  void onClose() {}

  ///下一步按钮是否可以点击
  checkCommitStatus() {
    if (typeModel.name != null &&
        typeDetailModel.name != null &&
        deviceNameController.text.isNotEmpty &&
        deviceSnController.text.isNotEmpty) {
      btnCanClick = true;
    } else {
      btnCanClick = false;
    }
    update();
  }

  ///选择单元
  Future<void> chooseUnit() async {
    showLoading(toast: ResKey.loading.tr);
    var result = await services.getOwningUnit(onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result != null) {
      deviceUnitList.clear();
      var resultList = result;
      resultList.forEach(
          (item) => deviceUnitList.add(AccessDeviceModel.fromJson(item)));
      List<String> list = deviceUnitList.map((e) => e.name ?? '').toList();
      showBottomPop(0, list);
    }
  }

  ///选择产品类型
  Future<void> chooseDeviceType() async {
    // if (unitMode.id == null) {
    //   showError('请先选择产品所属单元');
    //   return;
    // }
    // 隐藏键盘
    FocusScope.of(Get.context!).requestFocus(FocusNode());
    showLoading(toast: ResKey.loading.tr);
    var result = await services.getDeviceType({
      // 'subsystemId': unitMode.id,
      'isConfig': 0
    }, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result != null) {
      deviceTypeList.clear();
      var resultList = result;
      for (var element in resultList) {
        if (element['config'] != null) {
          Map<String, dynamic> map = json.decode(element['config']);
          Log.d('map===' + map.toString());
          if (map['selectDisplay'] != null && map['selectDisplay'] == 1) {
            deviceTypeList.add(DeviceTypeModel.fromJson(element));
          }
        }
      }
      // resultList.forEach((item) => deviceTypeList.add(DeviceTypeModel.fromJson(item)));
      List<String> list = deviceTypeList.map((e) => e.name ?? '').toList();
      showBottomPop(1, list);
    }
  }

  ///选择产品型号
  Future<void> chooseDeviceTypeDetail() async {
    // 隐藏键盘
    FocusScope.of(Get.context!).requestFocus(FocusNode());
    if (typeModel.id == null) {
      showError(ResKey.selectProductModel.tr);
      return;
    }
    showLoading(toast: ResKey.loading.tr);
    var result = await services.getProductModelList({
      'productTypeId': typeModel.id,
    }, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    if (result != null) {
      deviceTypeDetailList.clear();
      var resultList = result as List;
      for (var element in resultList) {
        if (element['config'] != null) {
          Map<String, dynamic> map = json.decode(element['config']);
          Log.d('config===' + element.toString());
          if (map['selectDisplay'] != null && map['selectDisplay'] == 1) {
            deviceTypeDetailList.add(DeviceTypeDetailModel.fromJson(element));
          }
        }
      }
      // ResKey.siteDeviceAccessEMSSNNumber
      // resultList.forEach((item) =>
      // deviceTypeDetailList.add(DeviceTypeDetailModel.fromJson(item)));
      List<String> list =
          deviceTypeDetailList.map((e) => e.model ?? '').toList();
      showBottomPop(2, list);
    }
  }

  // ///选择图片后的回调
  // void profilePictureCallback(
  //     {List<UploadJob>? uploadJobs, bool? pictureUploadProcessing}) {
  //   if (uploadJobs != null) {
  //     uploadJobList = uploadJobs;
  //     Log.d('uploadJobList==' + uploadJobList.toString());
  //     Log.d('uploadJobList==' + uploadJobList[0].toString());
  //   }
  // }

  ///下一步
  gotoNext() async {
    Log.d('gotoNext');
    // 隐藏键盘
    FocusScope.of(Get.context!).requestFocus(FocusNode());
    showLoading(toast: ResKey.loading.tr);
    var result = await services.deviceAccessConfigType(
        {'productId': typeDetailModel.id}, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    Log.d('result==' + result.toString());
    var params = {
      'siteId': siteId,
      'unitName': unitMode,
      'productType': typeModel,
      'productModel': typeDetailModel,
      'deviceName': deviceNameController.text ?? '',
      'deviceSn': deviceSnController.text ?? '',
      'imageList': deviceImageList
    };
    if (result != null) {
      ///paramConfigType 我们只需要关心1,2,4,6  1储能 2电表,4是逆变器 6是emsSn
      if (result['paramConfigType'] != null) {
        params['paramConfigType'] = result['paramConfigType'];
      }
      if (result['productConfigType'] != null) {
        params['productConfigType'] = result['productConfigType'];
      }
    }

    ///如果是风冷设备把sn换成emssn直接跳过第二步 直接到第三步,并把emsSn号通过config设置给params
    ///如果result['paramConfigType'] == null||['paramConfigType'].toString() == '0'直接去第三步
    if (result['paramConfigType'] == null ||
        (result['paramConfigType'] != null &&
            result['paramConfigType'].toString() == '0')) {
      var config = {
        'emsSn': deviceSnController.text ?? '',
      };
      params['config'] = jsonEncode(config);
      params['gotoComplete'] = true;
      Get.toNamed(RouterPath.siteDeviceAccessThree, arguments: params);
    } else {
      Get.toNamed(RouterPath.siteDeviceAccessTwo, arguments: params);
    }
  }

  ///弹出底部弹窗
  showBottomPop(int index, List<String> list) {
    //0为所属单元 1为产品类型 2为产品型号
    var title = ResKey.siteDeviceAccessOwningUnit.tr;
    if (index == 1) {
      title = ResKey.siteDeviceAccessProductType.tr;
    } else if (index == 2) {
      title = ResKey.siteDeviceAccessProductModel.tr;
    }

    BrnMultiDataPicker(
      context: Get.context!,
      title: title,
      createItemWidget:
          (bool isSelect, int column, int row, List selectedItems) {
        Log.d('selectedItems===' + selectedItems.toString());

        return Container(
          height: 44,
          alignment: Alignment.center,
          child: Text(
            list[row].toString(),
            textAlign: TextAlign.center,
            style: ytTextStyle(
                color: selectedItems != null &&
                        selectedItems.isNotEmpty &&
                        selectedItems.first == row
                    ? Colour.primaryColor
                    : Colour.lightTextColor,
                fontWeight: FontWeight.w500,
                fontSize: 18),
          ),
        );
      },
      confirmClick: (indexList) {
        Log.d('indexList==' + indexList.toString());
        if (index == 0) {
          unitMode = deviceUnitList[indexList[0]];
          typeModel = DeviceTypeModel();
          typeDetailModel = DeviceTypeDetailModel();
          unitController.text = unitMode.name!;
          deviceModelController.text = '';
          deviceTypeController.text = '';
        } else if (index == 1) {
          typeModel = deviceTypeList[indexList[0]];
          typeDetailModel = DeviceTypeDetailModel();
          deviceTypeController.text = typeModel.name!;
          deviceModelController.text = '';
        } else if (index == 2) {
          typeDetailModel = deviceTypeDetailList[indexList[0]];
          deviceModelController.text = typeDetailModel.model!;
          Map<String, dynamic> map =
              json.decode(typeDetailModel.config.toString());
          if (map['deviceConfig'] != null &&
              map['deviceConfig']['snName'] != null) {
            titleList[4] = map['deviceConfig']['snName'].toString();
          } else {
            titleList[4] = ResKey.deviceSn.tr;
          }
        }
        checkCommitStatus();
        update();
      },
      delegate: Brn1RowDelegate(list),
    ).show();
  }
}
